package bible.sunflower.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("===START=====");
		System.out.println("===END=====");
	}
	
	public static List<String> readFileByLine(String filepath ){		
		String line = "";
		List<String> lineList = new ArrayList<String>();
		try {
			FileReader fr = new FileReader( filepath );
			BufferedReader br = new BufferedReader( fr );
			while( ( line = br.readLine() ) != null ){
				if( line.trim().length() == 0 ){
					continue;
				}
				lineList.add( line );
			}
			br.close();
		} catch ( IOException e) {
			e.printStackTrace();
		}
		return lineList;
	}
	
	/**
	 * 查找出现重复内容的行号
	 * @param filepath
	 * @param prefix
	 * @param suffix
	 * @param duplicateCount  重复出现的次数
	 * @return
	 */
	public static Map<String,String> getLineNoOfDuplicateContent(String filepath, String prefix, String suffix, int duplicateCount ){
		Map<String, String> duplicateContentLineNoMap = new HashMap<String, String>();
		Map<String, Integer> countMap = new HashMap<String, Integer>();
		Map<String, String> lineNoMap = new HashMap<String, String>();
		try {
			FileReader fr = new FileReader( filepath );
			BufferedReader br = new BufferedReader( fr );
			String line = "";
			int lineNo = 0;
			while( (line = br.readLine()) != null ){
				lineNo++;
				int index = line.indexOf(prefix);
				if( index < 0 ){
					continue;
				}
				int endIndex = line.indexOf(suffix, index);
				if( endIndex < index ){
					continue;
				}
				String key = line.substring(index, endIndex + suffix.length() );
				if( countMap.containsKey(key) ){
					countMap.put(key, countMap.get(key) + 1 );
					lineNoMap.put(key, lineNoMap.get(key) + "," + lineNo );
				}else{
					countMap.put(key, 1);
					lineNoMap.put(key, "" + lineNo );
				}
				continue;
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		for( String key : countMap.keySet() ){
			if( countMap.get(key) >= duplicateCount ){
				duplicateContentLineNoMap.put(key, lineNoMap.get(key) );
			}
		}
		return duplicateContentLineNoMap;
	}
	
}
